package com.lagou.filter;

import com.lagou.common.RequestNode;
import com.lagou.common.TPMonitorContainer;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 接口响应性能监控拦截器
 *
 * @Author: zhangzhiwei
 * @Date: 2022/3/13 14:13
 */
@Activate(group = {CommonConstants.CONSUMER})
public class TPMonitorFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(TPMonitorFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {

        URL url = invoker.getUrl();
        String path = url.getPath();
        String methodName = invocation.getMethodName();
        long startTime = System.currentTimeMillis();
        Result result = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();

        long currentTime = System.currentTimeMillis();
        String key = path + methodName;
        TPMonitorContainer.offer(key, new RequestNode(currentTime, endTime - startTime));

        return result;

    }

}
